/*
 * ShoppingCartFragment.java
 * business
 *
 * Created by ChenTao on 2016/9/9.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.main.shoppingcart;

import android.content.DialogInterface;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yidiandao.business.R;
import com.yidiandao.business.base.SuperBaseEventFragment;
import com.yidiandao.business.data.bean.Goods;
import com.yidiandao.business.data.event.RefreshShoppingCartEvent;
import com.yidiandao.business.data.imagemodule.ImageAD;
import com.yidiandao.business.data.imagemodule.Notice;
import com.yidiandao.business.manager.ShoppingCartManager;
import com.yidiandao.business.ui.adapter.RecommendGoodsAdapter;
import com.yidiandao.business.ui.adapter.ShoppingCartAdapter;
import com.yidiandao.business.ui.main.MainActivity;
import com.yidiandao.business.ui.main.shoppingcart.confirmorder.ConfirmOrderActivity;
import com.yidiandao.business.ui.widget.dialog.BusinessDialog;
import com.yidiandao.business.ui.widget.dialog.LoadingDialog;
import com.yidiandao.business.ui.widget.listview.DisplayListItem;
import com.yidiandao.business.ui.widget.view.NoticeView;
import com.yidiandao.business.ui.widget.view.SpaceItemDecoration;
import com.yidiandao.business.ui.widget.view.SuperLoadingLayout;
import com.yidiandao.business.utils.ImageLoader;
import com.yidiandao.business.utils.JumpUtils;
import com.yidiandao.business.utils.TextRenderUtils;
import com.yidiandao.business.utils.UIUtils;
import com.yidiandao.business.utils.UmengUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * 购物车 页面 - View 层
 */
public class ShoppingCartFragment extends SuperBaseEventFragment
        implements ShoppingCartContract.View,
        View.OnClickListener,
        ShoppingCartManager.OnShoppingCartStatisticsListener,
        ShoppingCartManager.OnShoppingCartGoodsItemNumberChangeListener {

    public static final String TAG = ShoppingCartFragment.class.getSimpleName();

    private ShoppingCartContract.Presenter mPresenter;

    private TextView mTvRightEdit;

    private RelativeLayout mRlytEditLayout;

    private TextView mTvDelete;

    private RelativeLayout mRlytSelectAllToEdit;

    private RelativeLayout mRlytSelectAllToPay;

    private RelativeLayout mRlytPayLayout;

    private TextView mTvPay;

    private RecyclerView mRecyclerView;

    private ListView mListView;

    private ShoppingCartAdapter mAdapter;

    private CheckBox mCbSelectAllToEdit;

    private CheckBox mCbSelectAllToPay;

    private TextView mTvStatistics;

    private TextView mTvRandomGo;

    private LinearLayout mLlytRecommend;

    private PtrClassicFrameLayout mPtrFrame;

    private TextView mTvTotalWithReduce;

    private LoadingDialog mLoadingDialog;

    private ImageView mIvADImage;

    private NoticeView mNoticeView;

    private RecommendGoodsAdapter mRecommendGoodsAdapter;

    public static ShoppingCartFragment getInstance() {
        return new ShoppingCartFragment();
    }

    @Override
    protected void initViews() {

        mNoticeView = (NoticeView) mRootView.findViewById(R.id.marqueeView);

        mTvRightEdit = (TextView) mRootView.findViewById(R.id.tv_edit);
        mRlytEditLayout = (RelativeLayout) mRootView.findViewById(R.id.rlyt_edit_layout);
        mTvDelete = (TextView) mRootView.findViewById(R.id.tv_delete);
        mRlytSelectAllToEdit =
                (RelativeLayout) mRootView.findViewById(R.id.rlyt_select_all_to_edit);
        mRlytSelectAllToPay = (RelativeLayout) mRootView.findViewById(R.id.rlyt_select_all_to_pay);
        mRlytPayLayout = (RelativeLayout) mRootView.findViewById(R.id.rlyt_pay_layout);
        mTvPay = (TextView) mRootView.findViewById(R.id.tv_pay);
        mRecyclerView = (RecyclerView) mRootView.findViewById(R.id.recycler_view);
        mListView = (ListView) mRootView.findViewById(R.id.list_view);
        mCbSelectAllToEdit = (CheckBox) mRootView.findViewById(R.id.cb_select_all_to_edit);
        mCbSelectAllToPay = (CheckBox) mRootView.findViewById(R.id.cb_select_all_to_pay);
        mTvStatistics = (TextView) mRootView.findViewById(R.id.tv_statistics);
        mLlytRecommend = (LinearLayout) mRootView.findViewById(R.id.llty_recommend);
        mTvRandomGo = (TextView) mRootView.findViewById(R.id.tv_random_go);
        mPtrFrame = (PtrClassicFrameLayout) mRootView.findViewById(R.id.ptr_frame);
        mTvTotalWithReduce = (TextView) mRootView.findViewById(R.id.tv_price_with_reduce);
        mIvADImage = (ImageView) mRootView.findViewById(R.id.iv_ad_image);
        mLoadingDialog = new LoadingDialog(mActivity);
        mLoadingDialog.setCanceledOnTouchOutside(false);

        initListeners();
        initListView();
        initRecyclerView();

        ShoppingCartManager.getInstance().addOnShoppingCartStatisticsListener(this);
        ShoppingCartManager.getInstance().addOnShoppingCartGoodsItemNumberChangeListener(this);
    }

    @Override
    protected boolean isMultiLoadData() {
        return true;
    }

    @Override
    protected void startLoadData() {
        if (mPresenter.checkLogin()) {
            // 只有登录了才加载购物车
            // 切换到选择赠品页面，不需要刷新购物车
            mPresenter.start();
        }
    }

    private void initListView() {
        mAdapter = new ShoppingCartAdapter(mActivity);
        mListView.setAdapter(mAdapter);
    }

    private void initListeners() {
        mTvPay.setOnClickListener(this);
        mTvRightEdit.setOnClickListener(this);
        mTvDelete.setOnClickListener(this);
        mRlytSelectAllToEdit.setOnClickListener(this);
        mRlytSelectAllToPay.setOnClickListener(this);
        mTvRandomGo.setOnClickListener(this);

        // 下拉刷新
        mPtrFrame.setLastUpdateTimeRelateObject(this);
        mPtrFrame.setPtrHandler(
                new PtrDefaultHandler() {
                    @Override
                    public void onRefreshBegin(PtrFrameLayout frame) {
                        // 下拉时加载服务器列表
                        mPresenter.loadServerShoppingCartList();
                        // 下拉时将菜单设置为非编辑模式
                        mPresenter.initPayMenu();
                    }
                });
    }

    private void initRecyclerView() {

        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(
                new SpaceItemDecoration(0, 0, (int) UIUtils.getDimens(R.dimen.dimen_5), 0));

        mRecommendGoodsAdapter = new RecommendGoodsAdapter(getActivity(), TAG);
        mRecyclerView.setAdapter(mRecommendGoodsAdapter);
    }

    @Override
    public void setRecommendGoodsList(List<Goods> goodsList) {
        mLlytRecommend.setVisibility(View.VISIBLE);
        mRecommendGoodsAdapter.setData(goodsList);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_shopping_cart;
    }

    @Override
    public void setPresenter(ShoppingCartContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void setDisplayListItems(List<DisplayListItem> displayListItems) {
        mAdapter.setData(displayListItems);
    }

    @Override
    public String getPagerTag() {
        return TAG;
    }

    @Override
    public void showToast(String text) {
        UIUtils.showToast(text);
    }

    @Override
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshShoppingCartEvent event) {
        if (event.isRefreshShoppingCart()) {
            // 重新加载服务器列表
            mPresenter.loadServerShoppingCartList();
            // 下拉时将菜单设置为非编辑模式
            mPresenter.initPayMenu();
        } else {
            // 来自赠品选择页面
            // 需要先更新统计
            mPresenter.notifyShoppingCartStatisticsChanged();
            // 然后再刷新ListView UI
            notifyAdapterDataSetChanged();
        }
    }

    @Override
    public void setSelectAllCheckBoxState(boolean checked) {
        mCbSelectAllToPay.setChecked(checked);
        mCbSelectAllToEdit.setChecked(checked);
    }

    @Override
    public void notifyAdapterDataSetChanged() {
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_edit:
                mPresenter.showOrHidePayMenu();
                break;
            case R.id.tv_pay:
                mPresenter.postShoppingCartData();
                // mPresenter.checkStockAndBalance();
                break;
            case R.id.tv_delete:
                UmengUtils.onEvent(mActivity, R.string.umeng_shopping_cart_delete);
                mPresenter.checkHasSelectedGoodsToDelete();
                break;
            case R.id.rlyt_select_all_to_pay:
                selectOrCancelAllToPay();
                break;
            case R.id.rlyt_select_all_to_edit:
                selectOrCancelAllToEdit();
                break;
            case R.id.tv_random_go:
                UmengUtils.onEvent(mActivity, R.string.umeng_shopping_cart_random_go);
                switchHomeFragment();
                break;
        }
    }

    @Override
    public void showLoadingDialog() {
        if (!mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
        }
    }

    @Override
    public void dismissLoadingDialog() {
        if (mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void setPayButtonEnable(boolean enable) {
        mTvPay.setEnabled(enable);
    }

    @Override
    public void switchHomeFragment() {
        ((MainActivity) mActivity).randomToHome();
    }

    public void selectOrCancelAllToEdit() {
        boolean checked = mCbSelectAllToEdit.isChecked();
        ShoppingCartManager.getInstance().selectAllGoodsOfShoppingCart(!checked);
        notifyAdapterDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        setPayButtonEnable(true);
    }

    @Override
    public void onPause() {
        super.onPause();
        mNoticeView.pause();
    }

    @Override
    public void selectOrCancelAllToPay() {

        boolean checkedAll = mCbSelectAllToPay.isChecked();
        // 选中或反选购物车中的所有商品
        ShoppingCartManager.getInstance().selectAllGoodsOfShoppingCart(!checkedAll);
        notifyAdapterDataSetChanged();
    }

    @Override
    public void showDeleteGoodsHintDialog() {
        new BusinessDialog.Builder(mActivity)
                .setTitle(R.string.shopping_cart_delete_hint)
                .setMessage(R.string.cannot_revert)
                .setPositiveButton(R.string.think_about_delete, null)
                .setNegativeButton(
                        R.string.confirm_delete,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mPresenter.delete();
                            }
                        })
                .create()
                .show();
    }

    @Override
    public void toConfirmOrderActivity() {
        UmengUtils.onEvent(mActivity, R.string.umeng_shopping_cart_account);
        ConfirmOrderActivity.actionStart(mActivity, true);
    }

    @Override
    public void showOrHidePayMenuAndClearSelected(boolean showPayMenu) {
        showOrHidePayMenu(showPayMenu);

        // 每次切换 编辑/支付菜单 都需要清空购物车中的选择
        ShoppingCartManager.getInstance().selectAllGoodsOfShoppingCart(false);
        notifyAdapterDataSetChanged();
    }

    @Override
    public void showOrHidePayMenu(boolean showPayMenu) {
        // 底部支付菜单的处理
        mRlytPayLayout.setVisibility(showPayMenu ? View.VISIBLE : View.GONE);
        mRlytEditLayout.setVisibility(showPayMenu ? View.GONE : View.VISIBLE);
        mTvRightEdit.setText(showPayMenu ? R.string.shopping_cart_edit : R.string.shopping_cart_finish);
    }

    @Override
    public void refreshContent(int result) {
        setTopRightVisibility(result == SuperLoadingLayout.STATE_SUCCESS);
        superRefreshLayoutState(result);

        // 没有数据，则重置checkbox的状态
        if (result == SuperLoadingLayout.STATE_EMPTY) {
            setSelectAllCheckBoxState(false);
        }
    }

    @Override
    public void setTopRightVisibility(boolean visibility) {
        mTvRightEdit.setVisibility(visibility ? View.VISIBLE : View.GONE);
    }

    @Override
    public int checkResultObject(Object resultObject) {
        return superCheckListState(resultObject);
    }

    @Override
    public void setRefreshComplete() {
        mPtrFrame.refreshComplete();
    }

    @Override
    public void showStockNotEnoughOrPriceChangedDialog(String message) {
        new BusinessDialog.Builder(mActivity)
                .setTitle(message)
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(
                        R.string.confirm,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 重新加载服务器列表
                                mPresenter.loadServerShoppingCartList();
                                // 下拉时将菜单设置为非编辑模式
                                mPresenter.initPayMenu();
                            }
                        })
                .create()
                .show();
    }

    @Override
    public void setRecommendGoodsAdvert(final ImageAD advert) {
        mIvADImage.setVisibility(View.VISIBLE);
        ImageLoader.loadImageFitXY(mActivity, mIvADImage, advert.getImage());
        mIvADImage.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        UmengUtils.onEvent(mActivity, R.string.umeng_categray_to_active);
                        JumpUtils.clickImageAD(mActivity, advert);
                    }
                });
    }

    @Override
    public void setNoticeInfo(final List<Notice> noticeList) {
        mNoticeView.setVisibility(View.VISIBLE);
        List<String> titleList = new ArrayList<>();

        for (Notice notice : noticeList) {
            titleList.add(notice.getContent());
        }

        mNoticeView.setNoticeList(titleList);
        mNoticeView.setOnItemClickListener(
                new NoticeView.OnItemClickListener() {
                    @Override
                    public void onItemClick(TextView view, int position) {
                        UmengUtils.onEvent(mActivity, R.string.umeng_categray_to_notice);
                        JumpUtils.clickNotice(mActivity, noticeList.get(position));
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ShoppingCartManager.getInstance().removeOnShoppingCartStatisticsListener(this);
        ShoppingCartManager.getInstance().removeOnShoppingCartGoodsItemNumberChangeListener(this);
    }

    @Override
    public void notifyDataChanged() {
        // do nothing
    }

    @Override
    public void onPriceAndSelectedCountChanged(
            float totalPriceBeforeReduce,
            float totalPriceAfterReduce,
            float totalReducePrice,
            int totalSelectedCount) {

        // 统计价格与数量

        SpannableStringBuilder builder = new SpannableStringBuilder();

        // 中间的价格
        SpannableString totalMiddle = TextRenderUtils.getBeautyPriceWithColor(
                totalPriceAfterReduce + "", null, UIUtils.dp2px(16), UIUtils.dp2px(14), UIUtils.getColor(R.color.pink));
        // 总计:
        SpannableString totalPre = TextRenderUtils.getAppearanceText(
                getString(R.string.shopping_cart_total_pre), R.style.ShoppingCartTotalPricePre);
        // 数量:
        SpannableString totalSuf = TextRenderUtils.getAppearanceText(
                getString(R.string.shopping_cart_total_suf, totalSelectedCount + ""), R.style.ShoppingCartTotalPriceSuf);

        builder.append(totalPre);
        builder.append(totalMiddle);
        builder.append(totalSuf);

        // 合计：￥xxx.xx元(xx件)
        mTvStatistics.setText(builder);

        // 总价：￥xx 已优惠：xx
        mTvTotalWithReduce.setText(
                UIUtils.getString(
                        R.string.shopping_cart_price_total,
                        totalPriceBeforeReduce,
                        totalReducePrice));
    }

    @Override
    public void onAllGoodsCheckChanged(boolean isSelectedAllGoods) {
        setSelectAllCheckBoxState(isSelectedAllGoods);
    }

    @Override
    public void onShoppingCartGoodsItemNumberChanged(Goods goods) {
        mPresenter.loadCartListByWhenGoodsCountChanged(goods);
    }
}
